﻿
using GameSave.Common.Entities;
using GameSave.Common.Misc;
using GameSave.Impl.JobExecutor;
using GameSave.Infrastructure.Data;
using GameSave.Infrastructure.Entities;
using GameSave.Infrastructure.Interfaces;
using GameSave.Infrastructure.Message;
using GameSave.UI.Properties;
using GameSave.UI.UC;
using log4net;
using PropertyChanged;
using Quick;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;

namespace GameSave.UI
{
    [AddINotifyPropertyChangedInterface]
    public class MainWindowVM : QBindableAppBase, IInitializable
    {

        #region collections


        private ObservableCollection<Job> _jobList;

        public ObservableCollection<Job> JobList
        {
            get { return _jobList; }
            set { _jobList = value; }
        }

        private List<int> _saveOptions;

        public List<int> SaveLimitOptions
        {
            get { return _saveOptions; }
            set { _saveOptions = value; }
        }


        private ObservableCollection<GameSaveModel> _backupList;

        public ObservableCollection<GameSaveModel> BackUpList
        {
            get { return _backupList; }
            set { _backupList = value; }
        }

        #endregion


        #region public properties

        private Job _selectedJob;

        public Job SelectedJob
        {
            get { return _selectedJob; }
            set
            {
                if (value != null && value != _selectedJob)
                {
                    _selectedJob = value;
                    //展示当前备份项目的文件
                    if (BackUpList != null && _allGameSaveList != null)
                    {
                        BackUpList.Clear();
                        var currSaves = _allGameSaveList.Where(it => it.JobID == _selectedJob.JobId).OrderByDescending(it => it.CreateDate).ToList();

                        if (currSaves != null && currSaves.Any())
                        {
                            foreach (var saveModel in currSaves)
                            {
                                BackUpList.Add(saveModel);
                            } 
                        }

                    }
                }
            }
        }

        private int _selectedSaveLimit;

        public int SelectedSaveLimit
        {
            get { return _selectedSaveLimit; }
            set { _selectedSaveLimit = value; }
        }

        private GameSaveModel _selectedBackup;

        public GameSaveModel SelectedBackup
        {
            get { return _selectedBackup; }
            set { _selectedBackup = value; }
        }



        private int _age = 16;

        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }

        private string _msg;

        public string Message
        {
            get { return _msg; }
            set { _msg = value; }
        }


        private SolidColorBrush _msgBrush;

        public SolidColorBrush MsgBrush
        {
            get { return _msgBrush; }
            set { _msgBrush = value; }
        }

        private SysConfig _sysCfg;

        public SysConfig SysConfig
        {
            get { return _sysCfg; }
            set { _sysCfg = value; }
        }


        #endregion


        #region private properties

        private IMessageBox _msgBox;
        private List<GameSaveModel> _allGameSaveList;
        private static readonly ILog logger = LogManager.GetLogger("MainWindowVM");
        private static readonly string ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DefaultConfig.ConfigDirectory);
        private static readonly string jobConfigPath = Path.Combine(ConfigPath, DefaultConfig.JobConfigFileName);
        private static readonly string sysConfigPath = Path.Combine(ConfigPath, DefaultConfig.SysConfigFileName);
        private static readonly string gameSaveConfigPath = Path.Combine(ConfigPath, DefaultConfig.GameSaveConfigDirectory);
        private Dictionary<string, IJobExecutor> JobContainer;
        private SolidColorBrush blackBrush = new SolidColorBrush(Colors.Black);
        private SolidColorBrush alertBrush = new SolidColorBrush(Colors.Red);

        #endregion


        public MainWindowVM(IMessageBox msgB)
        {
            Age = 18;
            JobList = new ObservableCollection<Job>();
            SaveLimitOptions = new List<int> { 2, 5, 10, 20, 50, 100 };
            JobContainer = new Dictionary<string, IJobExecutor>();
            _allGameSaveList = new List<GameSaveModel>();
            BackUpList = new ObservableCollection<GameSaveModel>();
            MsgBrush = new SolidColorBrush(Colors.Black);
            _msgBox = msgB;
            //_qConfiguration = cfg;

            LoadConfig();

            Messenger.Register<NotifyMessage>(this, msg =>
            {
                PublishMessage(msg.Content, msg.IsAlert);
            });

            Messenger.Register<ConfirmBackupRenameMessage>(this, msg =>
            {
                if(SelectedBackup != null)
                {
                    SelectedBackup.EditStatus = false;
                }
            });

            Messenger.Register<ReloadJobMessage>(this, msg =>
            {
                if(msg.PrepareUpdateJob != null)
                {
                    //替换并保存
                   var remoteJob = this.JobList.FirstOrDefault(it => it.JobId == msg.PrepareUpdateJob.JobId);
                   if(remoteJob != null)
                    {
                        this.JobList.Remove(remoteJob);
                        this.JobList.Add(msg.PrepareUpdateJob);
                        SaveConfig();
                    }
                }
                else
                {
                    //从配置中重新加载
                    LoadConfig();
                }    
            });

            Messenger.Register<SetLanguageMessage>(this, msg =>
            {
                SetLanguage(msg);
            });

            Messenger.Register<NewBackupCreateMessage>(this, msg => OnNewBackupCreated(msg.NewBackup));

            PublishMessage($"已就绪.");
        }

        public void SetLanguage(SetLanguageMessage msg)
        {
            //Localization.SetCulture(cultureName);
            
        }

        public void LoadConfig()
        {
            //加载系统配置
            SysConfig = ConfigHelper.GetConfig<SysConfig>(sysConfigPath);
            //加载job
            List<Job> jobs = ConfigHelper.GetConfig<List<Job>>(jobConfigPath);
            if (jobs != null)
            {
                jobs = jobs.OrderByDescending(it => it.LastExecuteDate).ToList();
                SelectedJob = jobs.FirstOrDefault();
                JobList.Clear();
                foreach (Job job in jobs)
                {
                    JobList.Add(job);
                }
            }
            //加载所有存档配置信息
            _allGameSaveList = ConfigHelper.GetConfigList<GameSaveModel>(gameSaveConfigPath);
        }

        public void SaveConfig() 
        {
            ConfigHelper.SetConfig<List<Job>>(JobList.ToList(), jobConfigPath);
        }


        private void PublishMessage(string msg, bool isAlert = false, int customDelay = 3)
        {
            //持久化
            if(isAlert)
            {
                logger.Error(msg);
            }
            else
            {
                logger.Info(msg);
            }

            Message = msg;
            MsgBrush = blackBrush;

            if (isAlert)
            {
                MsgBrush = alertBrush;
            }
            else
            {
                //延迟后消息消失
                Task.Run(() =>
                {
                    Task.Delay(1000 * customDelay).Wait();
                    Message = string.Empty;
                });
            }
        }

        public void DeleteBackup(GameSaveModel saveModel = null)
        {
            if(saveModel != null)
            {
                SelectedBackup = saveModel;
            }
            if (SelectedBackup != null)
            {
                //首先，删除备份文件
                string desc = SelectedBackup.Desc;
                if (string.IsNullOrEmpty(SelectedBackup.BackupRelativePath))
                {
                    //没有记录备份文件夹相对路径，推算出来
                    string backupDirName = $"{SelectedBackup.CreateDate.ToString("yyyyMMdd")}_{SelectedBackup.CreateDate.ToString("HHmmss")}";
                    SelectedBackup.BackupRelativePath = $"{SelectedJob.JobId}\\{backupDirName}";
                }
                string backupDir = Path.Combine(SysConfig.SaveDirectory, SelectedBackup.BackupRelativePath);
                if(Directory.Exists(backupDir))
                {
                    Directory.Delete(backupDir, true);
                }
                //其次，删除配置文件
                _allGameSaveList.Remove(SelectedBackup);
                string currBackupJsonFullPath = Path.Combine(gameSaveConfigPath, $"{SelectedBackup.JobID}.json");
                //为处理此问题: ‘该类型的 CollectionView 不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改’
                System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
                {
                     BackUpList.Remove(SelectedBackup);
                }));
                ConfigHelper.SetConfig<List<GameSaveModel>>(BackUpList.ToList(), currBackupJsonFullPath);
                SelectedBackup = null;
                PublishMessage($"存档: '{desc}' 已删除(基于规则:'自动存档最多保留{SelectedJob.AutoSaveBackupLimit}份。').");
            }
        }

        public void AddJob()
        {
            if(string.IsNullOrEmpty(SysConfig.SaveDirectory))
            {
                _msgBox.Show($"未设置存档主目录，请先在系统设置中配置。");
                return;
            }

            JobEditWindow jobEditW = QServiceProvider.GetService<JobEditWindow>();
            jobEditW.VM.SetConfig(ConfigPath, SysConfig.SaveDirectory);
            if (jobEditW.ShowDialog() == true)
            {
                if (jobEditW.VM != null)
                {
                    jobEditW.VM.CurrentJob.JobId = Guid.NewGuid().ToString().Replace("-", "");
                    jobEditW.VM.CurrentJob.CreateDate = DateTime.Now;
                    jobEditW.VM.CurrentJob.LastExecuteDate = DateTime.Now;
                    JobList.Add(jobEditW.VM.CurrentJob);

                    PublishMessage($"任务 '{jobEditW.VM.CurrentJob.JobName}' 创建成功");

                }
            }

            //持久化到json中
            ConfigHelper.SetConfig<List<Job>>(JobList.ToList(), jobConfigPath);
        }

        public bool GetStartStopBtnEnable(Job type, bool isRunning)
        {
            //if(type == JoBType.手动备份.ToString())
            //{
            //    return true;
            //}
            //else
            //{
            //    return !isRunning;
            //}
            return false;
        }

        public void EditJob()
        {
            if (SelectedJob == null)
            {
                if (_msgBox.QuestionOKCancel("未选择任何任务") == MessageBoxResult.OK)
                {
                    return;
                }
            }
            else
            {
                JobEditWindow jobEditW = QServiceProvider.GetService<JobEditWindow>();
                jobEditW.VM.CurrentJob = SelectedJob;
                if (jobEditW.ShowDialog() == true)
                {
                    if (jobEditW.VM != null)
                    {
                        var updateRecord = JobList.FirstOrDefault(it => it.JobId == jobEditW.VM.CurrentJob.JobId);
                        if (updateRecord != null)
                        {
                            JobList.Remove(updateRecord);
                        }
                        JobList.Add(jobEditW.VM.CurrentJob);

                        ConfigHelper.SetConfig<List<Job>>(JobList.ToList(), jobConfigPath);
                    }
                }

            }
        }

        //object sender, MouseButtonEventArgs e
        public void LikeChanged()
        {
            if (SelectedJob != null)
            {
                SelectedJob.Like = !SelectedJob.Like;
                NotifyPropertyChanged("Like");
            }
        }

        public void OnNewBackupCreated(GameSaveModel newBackup)
        {
            if(SelectedJob == null)
            {
                PublishMessage("没有选择任务,存档处理失败。");
                return;
            }
            //在右侧列表刷新更新的文件
            _allGameSaveList.Add(newBackup);
            //清理自动存档
            var prepareDeleteBackups = _allGameSaveList.Where(it => it.JobID == newBackup.JobID && it.IsAutoSave == true && it.Like == false)
                .OrderByDescending(it => it.CreateDate)
                .Skip(SelectedJob.AutoSaveBackupLimit)
                .ToList();
            foreach(var backup in prepareDeleteBackups)
            {
                DeleteBackup(backup);
            }

            //刷新列表
            //为处理此问题: ‘该类型的 CollectionView 不支持从调度程序线程以外的线程对其 SourceCollection 进行的更改’
            System.Windows.Application.Current.Dispatcher.Invoke((Action)(() =>
            {
                BackUpList.Clear();
                var currSaves = _allGameSaveList.Where(it => it.JobID == newBackup.JobID).OrderByDescending(it => it.CreateDate).ToList();
                foreach (var saveModel in currSaves)
                {
                    BackUpList.Add(saveModel);
                }
            }));
            

            //持久化
            string currBackupJsonFullPath = Path.Combine(gameSaveConfigPath, $"{newBackup.JobID}.json");
            ConfigHelper.SetConfig<List<GameSaveModel>>(BackUpList.ToList(), currBackupJsonFullPath);

            var relatedJob = JobList.FirstOrDefault(it => it.JobId == newBackup.JobID);
            relatedJob.LastExecuteDate = newBackup.CreateDate;
            relatedJob.SaveOperationCount = newBackup.GameSaveSerialNum;
            PublishMessage($"任务 '{relatedJob.JobName}' 产生了一个新的存档({newBackup.CreateDate.ToString("HH:mm:ss")}).");
        }

        public void LoadBackup()
        {
            if (SelectedJob == null)
            {
                SystemSounds.Beep.Play();
                _msgBox.QuestionOKCancel("没有选择备份项目！");
                return;
            }

            if (SelectedBackup == null)
            {
                SystemSounds.Beep.Play();
                _msgBox.QuestionOKCancel("没有选择备份的文件！");
                return;
            }

            //把备份文件夹内文件全部复制到游戏存档文件夹
            if(string.IsNullOrEmpty(SelectedBackup.BackupRelativePath))
            {
                //没有记录备份文件夹相对路径，推算出来
                string backupDirName = $"{SelectedBackup.CreateDate.ToString("yyyyMMdd")}_{SelectedBackup.CreateDate.ToString("HHmmss")}";
                SelectedBackup.BackupRelativePath = $"{SelectedJob.JobId}\\{backupDirName}";
            }
            string backupDir = Path.Combine(SysConfig.SaveDirectory, SelectedBackup.BackupRelativePath);

            string[] backupFileInfoList = Directory.GetFiles(backupDir);//获取源文件夹中的所有文件完整路径
            foreach (string backupFileFullPath in backupFileInfoList)
            {
                string fileName = Path.GetFileName(backupFileFullPath);
                string destDirName = string.Empty;
                string destFileFullName = string.Empty;
                //判断是单文件备份，还是文件夹备份
                if (!string.IsNullOrEmpty(SelectedJob.TargetBackupFile))
                {
                    //取单备份的文件夹
                    destDirName = Path.GetDirectoryName(SelectedJob.TargetBackupFile);
                    destFileFullName = Path.Combine(destDirName, fileName);
                }
                else
                {
                    destDirName = SelectedJob.TargetBackupDirectory;
                    destFileFullName = Path.Combine(destDirName, fileName);
                }
                if (Directory.Exists(destDirName))
                {
                    File.Copy(backupFileFullPath, destFileFullName, true);
                }
                else
                {
                    _msgBox.Show($"游戏存档文件夹已不存在!\n{destDirName}");
                    break;
                }
            }

            PublishMessage($"存档 '{SelectedBackup.Desc}' 已载入.");


        }

        public void ManualCreateBackup()
        {
            if (SelectedJob == null)
            {
                SystemSounds.Beep.Play();
                _msgBox.QuestionOKCancel("没有选择备份项目！");
                return;
            }

            //将单个文件，或者整个文件夹的内容，复制到指定目录下
            DateTime now = DateTime.Now;
            string folderName = $"{now.ToString("yyyyMMdd")}_{now.ToString("HHmmss")}";

            string targetBaseDir = Path.Combine(SysConfig.SaveDirectory, SelectedJob.JobId);
            if (!Directory.Exists(targetBaseDir))
            {
                Directory.CreateDirectory(targetBaseDir);
            }
            string targetBackupDir = Path.Combine(targetBaseDir, folderName);
            if (!Directory.Exists(targetBackupDir))
            {
                Directory.CreateDirectory(targetBackupDir);
            }

            //判断是单文件还是文件夹
            if (!string.IsNullOrEmpty(SelectedJob.TargetBackupFile))
            {
                //backup a single file
                
                string fileName = Path.GetFileName(SelectedJob.TargetBackupFile);
                string targetFileFullName = Path.Combine (targetBackupDir, fileName);
                File.Copy(SelectedJob.TargetBackupFile, targetFileFullName, true);
                SelectedJob.SaveOperationCount += 1;
                string serialNumText = string.Format("{0:D3}", SelectedJob.SaveOperationCount);
                string saveDesc = $"存档{serialNumText}";
                OnNewBackupCreated(new GameSaveModel
                    {
                        BackupRelativePath = $"{SelectedJob.JobId}\\{folderName}",
                        CreateDate = now,
                        Desc = saveDesc,
                        GameSaveSerialNum = SelectedJob.SaveOperationCount,
                        JobID = SelectedJob.JobId,
                    }
                );

                //PublishMessage($"已手动备份存档({now.ToString("HH:mm:ss")}).");

            }
            else if(!string.IsNullOrEmpty(SelectedJob.TargetBackupDirectory))
            {
                //backup the dir

                string[] soureFileNameFullPathList = Directory.GetFiles(SelectedJob.TargetBackupDirectory);
                foreach(string fileFullName in soureFileNameFullPathList)
                {
                    string fileName = Path.GetFileName(fileFullName);
                    string destFileFullPath = Path.Combine(targetBackupDir, fileName);
                    File.Copy(fileFullName, destFileFullPath, true);    
                }
                SelectedJob.SaveOperationCount += 1;
                string serialNumText = string.Format("{0:D3}", SelectedJob.SaveOperationCount);
                string saveDesc = $"存档{serialNumText}";
                OnNewBackupCreated(new GameSaveModel
                    {
                        BackupRelativePath = $"{SelectedJob.JobId}\\{folderName}",
                        CreateDate = now,
                        Desc = saveDesc,
                        GameSaveSerialNum = SelectedJob.SaveOperationCount,
                        JobID = SelectedJob.JobId,
                    }
                );

                //PublishMessage($"已手动备份存档({now.ToString("HH:mm:ss")}).");

            }
            else
            {
                _msgBox.Show("没有设置存档目录或存档文件,手动备份失败！");
            }
        }


        public void SaveData()
        {
            PublishMessage("保存配置中...");
            //save job cfg
            ConfigHelper.SetConfig<List<Job>>(JobList.ToList(), jobConfigPath);
            //save backup cfg
            foreach(Job job in JobList) 
            {
                var gameSaves = _allGameSaveList.Where(it => it.JobID == job.JobId).OrderBy(it => it.CreateDate).ToList();
                string specificBackupCfgFullPath = Path.Combine(gameSaveConfigPath, $"{job.JobId}.json");
                ConfigHelper.SetConfig<List<GameSaveModel>>(gameSaves, specificBackupCfgFullPath);
            }
            PublishMessage("退出...");
        }


        public void OpenSystemConfigWin()
        {
            SysCfgWindow sysCfgWin = QServiceProvider.GetService<SysCfgWindow>();

            if (sysCfgWin.ShowDialog() == true)
            {
                //重载配置
                this.SysConfig = ConfigHelper.GetConfig<SysConfig>(sysConfigPath);
            }
        }

        public bool GetStartStopBtnEnable(string type, string isRunning)
        {
            return false;
        }

        public void AboutThis()
        {
            About aboutWin = QServiceProvider.GetService<About>();

            aboutWin.ShowDialog();
        }

        private ICommand _changeBackupLikeCmd;

        public ICommand ChangeBackupLikeCmd
        {
            get
            {
                if(_changeBackupLikeCmd== null)
                {
                    _changeBackupLikeCmd = new RelayCommand((p) =>
                    { 
                        if(SelectedBackup != null)
                        {
                            SelectedBackup.Like = !SelectedBackup.Like;
                        }
                    });
                }
                return _changeBackupLikeCmd;
            }
        }



        private ICommand _openJobDirCmd;

        public ICommand OpenJobWorkDirCmd
        {
            get
            {
                if(_openJobDirCmd == null)
                {
                    _openJobDirCmd = new RelayCommand((p) =>
                    {
                        if(SelectedJob == null)
                        {
                            _msgBox.Show("没有选择备份任务!");
                            return;
                        }
                        else
                        {
                            string jobWorkDir = Path.Combine(SysConfig.SaveDirectory, SelectedJob.JobId);
                            if(Directory.Exists(jobWorkDir))
                            {
                                Process.Start("explorer.exe", jobWorkDir);
                            }
                            else
                            {
                                _msgBox.Show($"任务文件夹已不存在!\n{jobWorkDir}");
                                return;
                            }
                        }
                    });
                }
                return _openJobDirCmd;
            }
        }


        private ICommand _mouseOverBackupCmd;

        public ICommand OnMouseOverBackupCmd
        {
            get
            {
                if(_mouseOverBackupCmd == null)
                {
                    _mouseOverBackupCmd = new RelayCommand((p) =>
                    {
                        if (p != null)
                        {
                            SelectedBackup = p as GameSaveModel; 
                        }
                    });
                }
                return _mouseOverBackupCmd;
            }
        }




        private ICommand likeCmd;

        public ICommand LikeChangeCmd
        {
            get
            {
                return likeCmd ?? new RelayCommand((p) =>
                {
                    if (SelectedJob != null)
                    {
                        SelectedJob.Like = !SelectedJob.Like;

                    }
                });
            }
        }

        private ICommand startJobCmd;

        public ICommand StartJobCmd
        {
            get
            {
                return startJobCmd ?? new RelayCommand((p) =>
                {
                    if (SelectedJob != null)
                    {
                        if (!JobContainer.ContainsKey(SelectedJob.JobId))
                        {
                            IJobExecutor exec = null;
                            if (SelectedJob.JobType == JoBType.单文件备份.ToString())
                            {
                                exec = QServiceProvider.GetService<FileChangedDependJobExecutor>();
                            }
                            else if (SelectedJob.JobType == JoBType.多文件备份.ToString())
                            {
                                exec = QServiceProvider.GetService<DirectoryChangedDependJobExecutor>();

                            }
                            else if(SelectedJob.JobType == JoBType.定时备份.ToString())
                            {
                                exec = QServiceProvider.GetService<TimerDependJobExecutor>();
                            }
                            else
                            {
                                PublishMessage($"未知的任务类型:'{SelectedJob.JobType}',启动失败", true, 10);
                                return;
                            }

                            exec.InitExecutor(new JobContext
                                {
                                    CurrentJob = SelectedJob
                                }, 
                                SysConfig,
                                Messenger);
                            //exec.OnJobExecuted += OnNewBackupCreated;
                            exec.Start();
                            JobContainer.Add(SelectedJob.JobId, exec);
                            SelectedJob.IsRunning = true;
                            PublishMessage($"任务 '{SelectedJob.JobName}' 已启动！");

                        }
                        else
                        {
                            IJobExecutor currentJobExec = null;
                            JobContainer.TryGetValue(SelectedJob.JobId, out currentJobExec);
                            if (currentJobExec != null)
                            {
                                currentJobExec.Start();
                                SelectedJob.IsRunning = true;
                            }
                            PublishMessage($"任务 '{SelectedJob.JobName}' 已恢复！");

                        }
                    }
                });
            }
        }

        private ICommand _stopJobCmd;

        public ICommand StopJobCmd
        {
            get
            {
                return _stopJobCmd ?? new RelayCommand((p) =>
                {
                    if (SelectedJob != null)
                    {
                        if (JobContainer.ContainsKey(SelectedJob.JobId))
                        {
                            IJobExecutor currentJobExec = null;
                            JobContainer.TryGetValue(SelectedJob.JobId, out currentJobExec);
                            if (currentJobExec != null)
                            {
                                currentJobExec.Stop();
                                SelectedJob.IsRunning = false;
                                PublishMessage($"任务 '{SelectedJob.JobName}' 已手动停止！");

                            }
                            else
                            {
                                _msgBox.Show("容器中没有找到相应的Executor\n停止任务失败!");
                            }
                        }
                    }
                });
            }
        }

        private ICommand _editBackupCmd;

        public ICommand EditBackupCmd
        {
            get
            {
                if (_editBackupCmd == null)
                {
                    _editBackupCmd = new RelayCommand((p) =>
                    {
                        if (SelectedBackup != null)
                        {
                            SelectedBackup.EditStatus = !SelectedBackup.EditStatus;
                            if (SelectedBackup.EditStatus == true)
                            {
                                Messenger.Send<BackupDescFocusMessage>(new BackupDescFocusMessage
                                {
                                    Selectedbackup = SelectedBackup
                                }); 
                            }
                            if (SelectedBackup.EditStatus == false)
                            {
                                //由编辑中 -> 不在编辑中，保存修改
                                string currBackupJsonFullPath = Path.Combine(gameSaveConfigPath, $"{SelectedBackup.JobID}.json");
                                ConfigHelper.SetConfig<List<GameSaveModel>>(BackUpList.ToList(), currBackupJsonFullPath);
                            }
                        }
                    });
                }
                return _editBackupCmd;
            }
        }


        private ICommand _openBackupDirCmd;

        public ICommand OpenBackupDirCmd
        {
            get
            {
                if (_openBackupDirCmd == null)
                {
                    _openBackupDirCmd = new RelayCommand((p) =>
                    {
                        if (SelectedBackup != null)
                        {
                            string relativeDirPath = SelectedBackup.BackupRelativePath;
                            string baseBackupDir = SysConfig.SaveDirectory;
                            string targetDir = Path.Combine(baseBackupDir, relativeDirPath);
                            if (Directory.Exists(targetDir))
                            {
                                Process.Start("explorer.exe", targetDir);
                            }
                            else
                            {
                                _msgBox.Show($"备份文件夹已不存在!\n{targetDir}");
                            }
                        }
                    });
                }
                return _openBackupDirCmd;
            }
        }

        private ICommand _loadBackupCmd;

        public ICommand LoadBackUpCmd
        {
           get
            {
                if(_loadBackupCmd == null)
                {
                    _loadBackupCmd = new RelayCommand((p) =>
                    {
                        LoadBackup();
                    });
                }
                return _loadBackupCmd;
            }
        }


        public void LikeBackup()
        {
            if (SelectedBackup != null)
            {
                ChangeBackupLikeCmd.Execute(null);
            }
        }

        public void DeleteJob()
        {
            if(SelectedJob == null)
            {
                _msgBox.Show("请先选择一个任务!");
                return;
            }

            MessageBoxResult result = _msgBox.QuestionYesNo($"确定要删除任务 '{SelectedJob.JobName}'?");
            if (result == MessageBoxResult.Yes)
            {

                //删除文件
                string backUpDir = Path.Combine(SysConfig.SaveDirectory, SelectedJob.JobId);
                if(Directory.Exists(backUpDir))
                {
                    Directory.Delete(backUpDir, true);
                }
                //删除任务的配置文件
                _allGameSaveList.RemoveAll(it => it.JobID == SelectedJob.JobId);

                //删除备份的配置文件
                var removeJob = JobList.FirstOrDefault(it => it.JobId == SelectedJob.JobId);
                JobList.Remove(removeJob);

                SelectedJob = null;

            }
        }

        public void OpenLogDir()
        {
            string logDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Logs");
            string dateFormat = DateTime.Today.ToString("yyyy-MM-dd");
            string logFileFullPath = Path.Combine(logDir, $"{dateFormat}.log");
            if(File.Exists(logFileFullPath))
            {
                Process.Start(logFileFullPath);
            }
            else if(Directory.Exists(logDir))
            {
                Process.Start("explorer.exe", logDir);

            }
        }

        public void Initialize()
        {
            Localization.RegisterCultureChangedHandler(this, l =>
            {
                PublishMessage($"切换语言到'{l.CurrentCulture.Name}'.");
            });
        }
    }
}
